<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <head th:include="include :: header"></head>
    <link href="/ajax/libs/iCheck/custom.css" th:href="@{/ajax/libs/iCheck/custom.css}" rel="stylesheet"/>
    <link href="/ajax/libs/datapicker/datepicker3.css" th:href="@{/ajax/libs/datapicker/datepicker3.css}" rel="stylesheet"/>
    <style>
        .droppable-active{background-color:#ffe!important}.tools a{cursor:pointer;font-size:80%}.form-body .col-md-6,.form-body .col-md-12{min-height:400px}.draggable{cursor:move}
    </style>
    <title>流量观察</title>
    <style>
        html,
        body {
            margin: 0;
            padding: 0;
            overflow: hidden;
            height: 100%;
        }

        #mapContainer {
            position: relative;
            height: 100%;
            width: 100%;
        }

        .clusterBubble {
            border-radius: 50%;
            color: #fff;
            font-weight: 500;
            text-align: center;
            opacity: 0.88;
            background-image: linear-gradient(139deg, #4294FF 0%, #295BFF 100%);
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.20);
            position: absolute;
            top: 0px;
            left: 0px;
        }
    </style>
</head>
<body onload="init()">
<form id="searchForm">
    <div style="margin-top: 15px;" class="btn-group hidden-xs" id="toolbar1" role="group">
        <div style="margin-left: -16px; margin-right: 16px" class="col-xs-3">
            <div class="col-sm-9" style="width: 108%">
                <div class="form-group">
                    <div class="input-group date">
                        <span class="input-group-addon">选择日期</span>
                        <input disabled id="currentTime"  type="text" class="form-control"
                               value="">
                    </div>
                </div>
            </div>
        </div>
        <label style="margin-left: 10px" type="button" class="btn btn-primary" onclick="search()" id=""><i
                class="fa fa-search"></i>&nbsp;搜索
        </label>
    </div>
</form>
<div id='mapContainer'>
    <div style="display: none" id="userDailyActivityList" class="panel-body">
        [[${userDailyActivityList}]]
    </div>
</div>
<div th:include="include :: footer"></div>
<script charset="utf-8" src="https://map.qq.com/api/gljs?v=1.exp&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77"></script>
<script src="/ajax/libs/iCheck/icheck.min.js" th:src="@{/ajax/libs/iCheck/icheck.min.js}"></script>
<script src="/ajax/libs//datapicker/bootstrap-datepicker.js" th:src="@{/ajax/libs//datapicker/bootstrap-datepicker.js}"></script>
<script src="/ajax/libs/beautifyhtml/beautifyhtml.js" th:src="@{/ajax/libs/beautifyhtml/beautifyhtml.js}"></script>
<script src="/static/reasahi/js/moment.js?v1.1.6" th:src="@{/reasahi/js/moment.js?v=1.1.6}"></script>
<script>
    var map;
    var ClusterBubbleClick;
    var usersLoginList = document.getElementById("userDailyActivityList").innerText;
    var userDailyActivityList = JSON.parse(usersLoginList);
    var geometrieList = [];
    userDailyActivityList.forEach(function (item) {
        geometrieList.push(  { // 点数组
            position: new TMap.LatLng(item.lat, item.lng),
            userId: item.userId
        });
    });

    function init() {

        var drawContainer = document.getElementById('mapContainer');

        var center = new TMap.LatLng(39.953416, 116.380945);

        map = new TMap.Map('mapContainer', {
            zoom: 4,
            pitch: 40,
            center: center
        });

        // 创建点聚合
        var markerCluster = new TMap.MarkerCluster({
            id: 'cluster',
            map: map,
            enableDefaultStyle: false, // 关闭默认样式
            minimumClusterSize: 2,
            geometries: geometrieList,
            zoomOnClick: true,
            gridSize: 60,
            averageCenter: false
        });

        var clusterBubbleList = [];
        var markerGeometries = [];
        var marker = null;

        // 监听聚合簇变化
        markerCluster.on('cluster_changed', function (e) {
            // 销毁旧聚合簇生成的覆盖物
            if (clusterBubbleList.length) {
                clusterBubbleList.forEach(function (item) {
                    item.destroy();
                })
                clusterBubbleList = [];
            }
            markerGeometries = [];

            // 根据新的聚合簇数组生成新的覆盖物和点标记图层
            var clusters = markerCluster.getClusters();
            clusters.forEach(function (item) {
                if (item.geometries.length > 1) {
                    let clusterBubble = new ClusterBubble({
                        map,
                        position: item.center,
                        content: item.geometries.length,
                    });
                    clusterBubble.on('click', () => {
                        initWindow(item.center.lat, item.center.lng,item.geometries);
                        infoWindow.open(); //打开信息窗
                    });
                    clusterBubbleList.push(clusterBubble);
                } else {
                    markerGeometries.push({
                        position: item.center,
                        userId:item.geometries[0].userId
                    });
                }
            });
            if (marker) {
                // 已创建过点标记图层，直接更新数据
                marker.setGeometries(markerGeometries);
            } else {
                // 创建点标记图层
                marker = new TMap.MultiMarker({
                    map,
                    styles: {
                        default: new TMap.MarkerStyle({
                            'width': 34,
                            'height': 42,
                            'anchor': {
                                x: 17,
                                y: 21,
                            },
                            'src': 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/marker_blue.png',
                        }),
                    },
                    geometries: markerGeometries
                });
                //监听点击事件添加marker
              marker.on("mouseover",function (obj) {
                  initWindow(obj.geometry.position.lat, obj.geometry.position.lng, obj.geometry.userId);
                  infoWindow.open(); //打开信息窗
              });
            }
            if(infoWindow){
                infoWindow.close();
            }
        });
    }

    // 以下代码为基于DOMOverlay实现聚合点气泡
    function ClusterBubble(options) {
        TMap.DOMOverlay.call(this, options);
    }

    ClusterBubble.prototype = new TMap.DOMOverlay();

    ClusterBubble.prototype.onInit = function (options) {
        this.content = options.content;
        this.position = options.position;
    };

    // 销毁时需要删除监听器
    ClusterBubble.prototype.onDestroy = function() {
        this.dom.removeEventListener('click', this.onClick);
        this.removeAllListeners();
    };

    ClusterBubble.prototype.onClick = function() {
        this.emit('click');

    };
    // 创建气泡DOM元素
    ClusterBubble.prototype.createDOM = function () {
        var dom = document.createElement('div');
        dom.classList.add('clusterBubble');
        dom.innerText = this.content;
        dom.style.cssText = [
            'width: ' + (40 + parseInt(this.content) * 2) + 'px;',
            'height: ' + (40 + parseInt(this.content) * 2) + 'px;',
            'line-height: ' + (40 + parseInt(this.content) * 2) + 'px;',
        ].join(' ');

        // 监听点击事件，实现zoomOnClick
        this.onClick = this.onClick.bind(this);
        // pc端注册click事件，移动端注册touchend事件
        dom.addEventListener('click', this.onClick);
        return dom;
    };

    ClusterBubble.prototype.updateDOM = function () {
        if (!this.map) {
            return;
        }
        // 经纬度坐标转容器像素坐标
        let pixel = this.map.projectToContainer(this.position);

        // 使文本框中心点对齐经纬度坐标点
        let left = pixel.getX() - this.dom.clientWidth / 2 + 'px';
        let top = pixel.getY() - this.dom.clientHeight / 2 + 'px';
        this.dom.style.transform = `translate(${left}, ${top})`;

        this.emit('dom_updated');
    };

    window.ClusterBubble = ClusterBubble;


    var infoWindow;
    // 初始化一个信息窗口
    function initWindow(lat, lng,values) {
        // 一次只能打开一个窗口 打开之前先关闭之前打开的
        if (infoWindow) {
            infoWindow.close();//初始关闭信息窗关闭
        }
        infoWindow = new TMap.InfoWindow({
            map: map,
            position: new TMap.LatLng(lat, lng),
            offset: { x: 0, y: -30 }, //设置信息窗相对position偏移像素
        });
        var htmlValue = "";
        if(values instanceof Array){
            values.forEach(function (item) {
                htmlValue = htmlValue + '<p style="  margin: 0;\n' +
                    '    padding: 0;">' + item.userId + '</p>';
            });
        }else{
            htmlValue = htmlValue + '<p style="  margin: 0;\n' +
                '    padding: 0;">' + values + '</p>';
        }
        infoWindow.setContent('<div>'
            + '<div>'
            + '用户ID'
            + '</div>'
            + '<div>'
            + ' <div>'
            + htmlValue
            + '</div>'
            + '</div>'
            + '</div>'
        );//设置信息窗内容
    }
</script>
<script>
    $(document).ready(function(){setup_draggable();$("#n-columns").on("change",function(){var v=$(this).val();if(v==="1"){var $col=$(".form-body .col-md-12").toggle(true);$(".form-body .col-md-6 .draggable").each(function(i,el){$(this).remove().appendTo($col)});$(".form-body .col-md-6").toggle(false)}else{var $col=$(".form-body .col-md-6").toggle(true);$(".form-body .col-md-12 .draggable").each(function(i,el){$(this).remove().appendTo(i%2?$col[1]:$col[0])});$(".form-body .col-md-12").toggle(false)}});$("#copy-to-clipboard").on("click",function(){var $copy=$(".form-body").clone().appendTo(document.body);$copy.find(".tools, :hidden").remove();$.each(["draggable","droppable","sortable","dropped","ui-sortable","ui-draggable","ui-droppable","form-body"],function(i,c){$copy.find("."+c).removeClass(c).removeAttr("style")});var html=html_beautify($copy.html());$copy.remove();$modal=get_modal(html).modal("show");$modal.find(".btn").remove();$modal.find(".modal-title").html("复制HTML代码");$modal.find(":input:first").select().focus();return false})});var setup_draggable=function(){$(".draggable").draggable({appendTo:"body",helper:"clone"});$(".droppable").droppable({accept:".draggable",helper:"clone",hoverClass:"droppable-active",drop:function(event,ui){$(".empty-form").remove();var $orig=$(ui.draggable);if(!$(ui.draggable).hasClass("dropped")){var $el=$orig.clone().addClass("dropped").css({"position":"static","left":null,"right":null}).appendTo(this);var id=$orig.find(":input").attr("id");if(id){id=id.split("-").slice(0,-1).join("-")+"-"+(parseInt(id.split("-").slice(-1)[0])+1);$orig.find(":input").attr("id",id);$orig.find("label").attr("for",id)}$('<p class="tools col-sm-12 col-sm-offset-3">						<a class="edit-link">编辑HTML<a> | 						<a class="remove-link">移除</a></p>').appendTo($el)}else{if($(this)[0]!=$orig.parent()[0]){var $el=$orig.clone().css({"position":"static","left":null,"right":null}).appendTo(this);$orig.remove()}}}}).sortable()};var get_modal=function(content){var modal=$('<div class="modal" style="overflow: auto;" tabindex="-1">	<div class="modal-dialog"><div class="modal-content"><div class="modal-header"><a type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</a><h4 class="modal-title">编辑HTML</h4></div><div class="modal-body ui-front">	<textarea class="form-control" 	style="min-height: 200px; margin-bottom: 10px;font-family: Monaco, Fixed">'+content+'</textarea><button class="btn btn-success">更新HTML</button></div>				</div></div></div>').appendTo(document.body);return modal};$(document).on("click",".edit-link",function(ev){var $el=$(this).parent().parent();var $el_copy=$el.clone();var $edit_btn=$el_copy.find(".edit-link").parent().remove();var $modal=get_modal(html_beautify($el_copy.html())).modal("show");$modal.find(":input:first").focus();$modal.find(".btn-success").click(function(ev2){var html=$modal.find("textarea").val();if(!html){$el.remove()}else{$el.html(html);$edit_btn.appendTo($el)}$modal.modal("hide");return false})});$(document).on("click",".remove-link",function(ev){$(this).parent().parent().remove()});
    $(document).ready(function(){$(".i-checks").iCheck({checkboxClass:"icheckbox_square-green",radioClass:"iradio_square-green",})});
    $(".input-group.date").datepicker({todayBtn: "linked",keyboardNavigation: !1,forceParse: !1,calendarWeeks: !0,autoclose: !0});
    var value = "[[${currentTime}]]";
    var startCreatTime = moment().hours(0).minutes(0).seconds(0);
    if(value){
        startCreatTime =  value;
    }else{
        startCreatTime = startCreatTime.format('YYYY-MM-DD');
    }
    $("#currentTime").val(startCreatTime);
    function search(){
        window.location.href ="/manage/userAgent/traffic_observation?currentTime=" +  $("#currentTime").val();
    }

</script>
</body>

</html>